Java Exception Handling
There is always the possibility of errors occurring during the normal flow of a programme in any programming language. Handling the errors is known as Exception Handling
.
We use try/catch
block to handle exceptions.
You can specify a set of codes to be tested for errors inside the try
statement and catch
block containing the code to be executed if any error occurs.
Syntax for try/catch block
try
{
// set of codes to try
}
catch(Exception ex)
{
// codes to handle error
}
Example for try/catch block
public class Main {
public static void main(String[ ] args) {
try {
int[] numbers = {4,5,6};
System.out.println(numbers[5]);
} catch (Exception e) {
System.out.println("Index out of range.");
}
}
}
Output
Index out of range.
Finally Statement
The finally
block is executed irrespective of try
or catch
block execution.
Example for finally statement
public class Main {
public static void main(String[ ] args) {
try {
int[] numbers = {4,5,6};
System.out.println(numbers[5]);
} catch (Exception e) {
System.out.println("Index out of range.");
}
finally{
System.out.println("End of try-catch block");
}
}
}
Throw Exception
With the help of throw
keyword it is possible to create custom error.
Example for throwing error and handling it
public class Main {
static void checkAge(int age) {
try{
if (age < 18) {
throw new Exception("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted.");
}
} catch(Exception ex){
System.out.println(ex);
}
}
public static void main(String[] args) {
checkAge(15);
}
}
Output
java.lang.Exception: Access denied - You must be at least 18 years old.